package intranet.controllers;
import org.springframework.web.servlet.ModelAndView;
import intranet.models.*;
import intranet.tools.*;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class MyuploadController extends HttpServlet {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	/* IsNumber Function */
	public static boolean IsNumber(String num) {
        try {
            Integer.parseInt(num);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
	
	@RequestMapping("myuploads.html")
	public ModelAndView Myuploads(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			int category=0;
			category=(IsNumber(request.getParameter("txtcat")))?Integer.parseInt(request.getParameter("txtcat")):0;
			String page= request.getParameter("page");
			MyuploadModel Myupload=new MyuploadModel();
			
			/* Login Session - User_ID=2*/
			ResultSet rs=(category==0)?Myupload.SelectMyupload(Integer.parseInt(session.getAttribute("user_id").toString())):Myupload.SelectMyuploadByCategory((Integer.parseInt(session.getAttribute("user_id").toString())), category);
			ArrayList Myuploads=this.resultSetToArrayList(rs);
			int RowCount=Myuploads.size();
			//Passing Page Included
			mv.addObject("includethispage", "file_sharing/myupload/myuploads.jsp");
			// Passing Data Record
			mv.addObject("data", Myuploads);
			
			// Passing File Category
			FileCategoryModel mycat=new FileCategoryModel();
			ResultSet rscat=mycat.SelectFileCategory(0);
			ArrayList cat=this.resultSetToArrayList(rscat);
			mv.addObject("categories",cat);
			// Passing Current Category
			mv.addObject("curcategory",category);
			
			// Pagination Link Elements
			page=(page==null || IsNumber(page)==false)?"1":page;
			int PageSize=15;
			int PageCount=((RowCount%PageSize)>0)?Math.round(RowCount/PageSize)+1:Math.round(RowCount/PageSize);
			page=(Integer.parseInt(page)<=0 ||Integer.parseInt(page)>PageCount)?"1":page;
			int StartingRow=(Integer.parseInt(page)-1)*PageSize;
			int EndingRow=(Integer.parseInt(page)*PageSize)-1;
			mv.addObject("page", page);
			mv.addObject("PageCount", PageCount);
			mv.addObject("StartingRow", StartingRow);
			mv.addObject("EndingRow", EndingRow);
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("edit_myupload.html")
	public ModelAndView EditMyuploads(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			String file_id= request.getParameter("file_id");
			file_id=(file_id==null || IsNumber(file_id)==false)?"0":file_id;
			file_id=(Integer.parseInt(file_id)<=0)?"0":file_id;
			/* IF Requested ID=0 */
			if(Integer.parseInt(file_id)==0){
				mv.addObject("includethispage", "not_accessible_page.jsp");
				return mv;
			}else{
				MyuploadModel Myupload=new MyuploadModel();
				// Verify File Owner
				if(Myupload.isOwner(Integer.parseInt(session.getAttribute("user_id").toString()), Integer.parseInt(file_id))==false){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}
				FileCategoryModel CategoryModel=new FileCategoryModel();
				ResultSet rs=Myupload.SelectUploadedFile(Integer.parseInt(file_id));
				ResultSet rscat=CategoryModel.SelectFileCategory(0);
				ArrayList Myuploads=this.resultSetToArrayList(rs);
				ArrayList FileCategories=this.resultSetToArrayList(rscat);
				//Passing Page Included
				mv.addObject("includethispage", "file_sharing/myupload/edit_myupload.jsp");
				// Passing Data Record & Image_File
				mv.addObject("data", Myuploads);
				// Passing ALL FILE CATEGORIES
				mv.addObject("categories", FileCategories);
				// Passing file id
				String keywords=Myupload.SelectFileKeywords(Integer.parseInt(file_id));
				mv.addObject("keywords",keywords);
				// Passing Web URL
				WebConfig con=new WebConfig();
				String URL=con.getURL();
				mv.addObject("weburl",URL);
				return mv;
			}	
			
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("/update_myuploads.html")
	public void UpdateMyuploads(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		if(session.getAttribute("user_id")!=null){
			String id= request.getParameter("txtid");
			String title=request.getParameter("txttitle");
			String cat_id=request.getParameter("txtcat");
			String file_desc=request.getParameter("txtdesc");
			String keywords=request.getParameter("txtkeyword");
			MyuploadModel Myuploads=new MyuploadModel();
			Myuploads.UpdateMyupload(Integer.parseInt(id),title,Integer.parseInt(cat_id),file_desc,keywords);
			response.sendRedirect("myuploads.html");
		}else{
			response.sendRedirect("login.html");
		}
		
	}
	
	@RequestMapping("/delete_myupload.html")
	public ModelAndView DeleteMyupload(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			String id= request.getParameter("file_id");
			MyuploadModel Myupload=new MyuploadModel();
			id=(IsNumber(id)?id:"0");
			if(Integer.parseInt(id)==0){
				mv.addObject("includethispage", "not_accessible_page.jsp");
				return mv;
			}else{
				// Verify File Owner
				if(Myupload.isOwner(Integer.parseInt(session.getAttribute("user_id").toString()), Integer.parseInt(id))==false){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}
				MyuploadModel Myuploads=new MyuploadModel();
				Myuploads.DeleteMyupload(Integer.parseInt(id));
				response.sendRedirect("myuploads.html");
			}
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("/upload_success.html")
	public ModelAndView uploadSuccess(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			mv.addObject("includethispage", "file_sharing/myupload/upload_success.jsp");
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
		
	}
	
	@RequestMapping("/upload_file.html")
	public ModelAndView ShowUploadPage(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){
			//Passing Page Included
			mv.addObject("includethispage", "file_sharing/myupload/upload.jsp");
			
			// Passing File Category
			FileCategoryModel mycat=new FileCategoryModel();
			ResultSet rscat=mycat.SelectFileCategory(0);
			ArrayList cat=this.resultSetToArrayList(rscat);
			mv.addObject("categories",cat);
			
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("/share_file.html")
	public ModelAndView ShareFile(HttpServletRequest request, HttpServletResponse response,String error_msg1,String error_msg2,String file_id,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView("index");
		if(session.getAttribute("user_id")!=null){	
			String fileID=(file_id=="")?request.getParameter("file_id"):file_id;
			if(!IsNumber(fileID)){
				mv.addObject("includethispage", "not_accessible_page.jsp");
				return mv;
			}else{
				MyuploadModel myMod=new MyuploadModel();
				// Verify File Owner
				if(myMod.isOwner(Integer.parseInt(session.getAttribute("user_id").toString()), Integer.parseInt(fileID))==false){
					mv.addObject("includethispage", "not_accessible_page.jsp");
					return mv;
				}
				
				//Passing Page Included
				mv.addObject("includethispage", "file_sharing/myupload/share_file.jsp");
				//Passing fileid
				mv.addObject("fileid",fileID);
				//Passing Users Shared
				ResultSet rstuser=myMod.SelectUsersShared(Integer.parseInt(fileID));
				ArrayList arruser=this.resultSetToArrayList(rstuser);
				mv.addObject("users", arruser);
				
				//Get File Owner ID and Pass to Page
				int ownerId=0;
				ResultSet fileRst=myMod.SelectUploadedFile(Integer.parseInt(fileID));
				while(fileRst.next()){
					ownerId=fileRst.getInt("USER_UPLOAD");
				}
				mv.addObject("ownerid", ownerId);
				
				
				//Passing Groups Shared
				ResultSet rstgrp=myMod.SelectGroupsShared(Integer.parseInt(fileID));
				ArrayList arrgrp=this.resultSetToArrayList(rstgrp);
				mv.addObject("groups", arrgrp);
				
				//Passing String of User Names
				String usernames=myMod.SelectUsers();
				mv.addObject("usernames",usernames);
				
				//Passing All Groups Belong to This User - USING SESSION FOR USER NAME
				ResultSet rstmygrp=myMod.SelectMyGroups(Integer.parseInt(session.getAttribute("user_id").toString()));
				ArrayList arrmygrp=this.resultSetToArrayList(rstmygrp);
				mv.addObject("mygroups",arrmygrp);
				
				//IF Error Occurred, passing error message to page
				mv.addObject("error_msg1",error_msg1);
				mv.addObject("error_msg2",error_msg2);
				
			}
		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping(value="/add_accessible_group.html",method = RequestMethod.POST)
	public ModelAndView AddFileGroup(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView();
		if(session.getAttribute("user_id")!=null){	
			MyuploadModel myMod=new MyuploadModel();
			String error_msg1="";
			String error_msg2="";
			String group_id=request.getParameter("txtgroup");
			String file_id="";
			if(request.getParameter("btngroup")!=""){
				file_id=request.getParameter("txtfileid2");
				if(myMod.isExistingGroup(group_id, file_id)){
					String group_name=myMod.SelectGroupNameById(group_id);
					error_msg1="";
					error_msg2="The group '"+group_name+"' has been added already";
					mv=this.ShareFile(request, response, error_msg1,error_msg2,file_id,session);
					return mv;
				}else{
					// Add File Group
					myMod.AddGroup(Integer.parseInt(file_id),Integer.parseInt(group_id));
					myMod.setShareStatus(Integer.parseInt(file_id));
					mv=this.ShareFile(request, response, error_msg1,error_msg2,file_id,session);
				}
			}

		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping("/delete_file_group.html")
	public void DeleteFileGroup(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		if(session.getAttribute("user_id")!=null){	
			String group_id=request.getParameter("group_id");
			String file_id=request.getParameter("file_id");
			if(IsNumber(group_id)==true && IsNumber(file_id)==true){
				MyuploadModel myMod=new MyuploadModel();
				myMod.DeleteGroup(Integer.parseInt(file_id),Integer.parseInt(group_id));
				myMod.setShareStatus(Integer.parseInt(file_id));
			}
			response.sendRedirect("share_file.html?file_id="+file_id);
		}else{
			response.sendRedirect("login.html");
		}
	}
	
	@RequestMapping(value="/add_accessible_user.html",method = RequestMethod.POST)
	public ModelAndView AddFileUser(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView();
		if(session.getAttribute("user_id")!=null){		
			MyuploadModel myMod=new MyuploadModel();
			String error_msg1="";
			String error_msg2="";
			String user_name=request.getParameter("txtusername");
			String file_id="";
			int user_id=myMod.getUserIdByUserName(user_name);
			if(request.getParameter("btnuser")!=""){
				file_id=request.getParameter("txtfileid1");
				if(user_name.isEmpty()){
					error_msg2="";
					error_msg1="Please enter user name";
					mv=this.ShareFile(request, response, error_msg1,error_msg2,file_id,session);
					return mv;
				}else if(user_id==0){
					error_msg2="";
					error_msg1="Incorrect user name, please try again";
					mv=this.ShareFile(request, response, error_msg1,error_msg2,file_id,session);
					return mv;
				}else if(myMod.isExistingUser(user_name,file_id)){
					error_msg2="";
					error_msg1="The user name '"+user_name+"' has been added already";
					mv=this.ShareFile(request, response, error_msg1,error_msg2,file_id,session);
					return mv;
				}else if(Integer.parseInt(session.getAttribute("user_id").toString())==user_id){
					error_msg2="";
					error_msg1="By default, your file is shared to you automatically";
					mv=this.ShareFile(request, response, error_msg1,error_msg2,file_id,session);
					return mv;
				}else{
					// Add File User
					myMod.AddUser(Integer.parseInt(file_id),user_id);
					myMod.setShareStatus(Integer.parseInt(file_id));
					mv=this.ShareFile(request, response, error_msg1,error_msg2,file_id,session);
				}
			}

		}else{
			response.sendRedirect("login.html");
		}
		return mv;
	}
	
	@RequestMapping(value="/delete_file_user.html",method = RequestMethod.GET)
	public void DeleteFileUser(HttpServletRequest request, HttpServletResponse response,HttpSession session) throws SQLException, IOException{
		ModelAndView mv=new ModelAndView();
		if(session.getAttribute("user_id")!=null){	
			String user_id=request.getParameter("user_id");
			String file_id=request.getParameter("file_id");
			if(IsNumber(user_id)==true && IsNumber(file_id)==true){
				MyuploadModel myMod=new MyuploadModel();
				myMod.DeleteUser(Integer.parseInt(file_id),Integer.parseInt(user_id));
				myMod.setShareStatus(Integer.parseInt(file_id));
			}
			response.sendRedirect("share_file.html?file_id="+file_id);
		}else{
			response.sendRedirect("login.html");
		}
	}
	// RESULTSET TO ARRAYLIST
	   public ArrayList resultSetToArrayList(ResultSet rs) throws SQLException{
		    ResultSetMetaData md = rs.getMetaData();
		    int columns = md.getColumnCount();
		    ArrayList results = new ArrayList();
		    while (rs.next()){
		    HashMap row = new HashMap();
		    results.add(row);
			    for(int i=1; i<=columns; i++){
			    row.put(md.getColumnName(i),rs.getObject(i));
			    }
		    }
		    return results;

	    }
}